<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="resources/shadow-dom.js"></script>
</head>
<body>
<p id="description"></p>
<div id="sandbox"></div>
<pre id="console"></pre>
<script>
description("Tests to ensure that accesskey works in regard to shadow DOM boundary. Can only run within DRT.");

function pressAccessKey(key)
{
    if (navigator.userAgent.search(/\bMac OS X\b/) != -1)
        modifiers = ["ctrlKey", "altKey"];
    else
        modifiers = ["altKey"];
    eventSender.keyDown(key, modifiers);
}

var eventRecords = {};

function clearEventRecords()
{
    eventRecords = {};
}

function dispatchedEvent(eventType)
{
    var events = eventRecords[eventType];
    if (!events)
        return [];
    return events;
}

function recordEvent(event)
{
    var eventType = event.type
    if (!eventRecords[eventType]) {
        eventRecords[eventType] = []
    }
    eventRecords[eventType].push(event.target.id);
}

function prepareDOMTree(parent)
{
    parent.appendChild(
        createDOM('div', {'id': 'divA'},
                  createDOM('input', {'id': 'inputB'}),
                  createDOM('div', {'id': 'shadowC', 'tabindex': 0},
                            createShadowRoot(
                                createDOM('input', {'id': 'inputD'}),
                                createDOM('input', {'id': 'inputE', 'accesskey': 'a'}),
                                createDOM('div', {'id': 'shadowF', 'tabindex': 0},
                                          createShadowRoot(
                                              createDOM('input', {'id': 'inputG'})))))));

    var ids = ['inputB',
               'shadowC/inputD', 'shadowC/inputE',
               'shadowC/shadowF/inputG'];
    for (var i = 0; i < ids.length; ++i) {
        var element = getNodeInComposedTree(ids[i]);
        element.addEventListener('focus', recordEvent, false);
    }
}

function test()
{
    prepareDOMTree(document.getElementById('sandbox'));

    // Please see the discussion of https://bugs.webkit.org/show_bug.cgi?id=67096.
    // We don't have a clear idea how accesskey should work in regard to shadow DOM.
    // In current implementation, accesskeys defined inside of components are exposed to an outer document.
    // Every accesskeys are flattened per each document.
    document.getElementById('inputB').focus();
    clearEventRecords();
    pressAccessKey('a');
    shouldBe('dispatchedEvent("focus")', '["inputE"]');

    getNodeInComposedTree('shadowC/inputD').focus();
    clearEventRecords();
    pressAccessKey('a');
    shouldBe('dispatchedEvent("focus")', '["inputE"]');

    getNodeInComposedTree('shadowC/shadowF/inputG').focus();
    clearEventRecords();
    pressAccessKey('a');
    shouldBe('dispatchedEvent("focus")', '["inputE"]');
}

test();
</script>
</body>
</html>
